﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace WMS.Common
{
    public class EmailTemplateHelper
    {
        /// <summary>
        /// 异步发送
        /// </summary>
        /// <param name="toEmail">收件人邮箱</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件内容</param>
        /// <returns></returns>
        public static async Task<bool> SendAsync(string toEmail, string subject, string body)
        {
            try
            {
                using (var mailMessage = new MailMessage())
                using (var client = new SmtpClient())
                {
                    // 配置邮件
                    mailMessage.From = new MailAddress(AppSettings.app("Email"));  // 发件人
                    mailMessage.To.Add(toEmail);                                   // 收件人
                    mailMessage.Subject = subject;                                 // 邮件主题
                    mailMessage.Body = body;                                       // 邮件内容
                    mailMessage.IsBodyHtml = true;                                 // 支持HTML格式

                    // 配置SMTP客户端
                    client.Host = AppSettings.app("SmtpHost") ?? "smtp.qq.com";    // SMTP服务器
                    client.Port = int.Parse(AppSettings.app("SmtpPort") ?? "587"); // 端口号
                    client.EnableSsl = true;                                       // 启用SSL加密
                    client.UseDefaultCredentials = false;                          // 不使用默认凭据
                    client.Credentials = new NetworkCredential(                    // 登录凭据
                        AppSettings.app("Email"),                                  // 邮箱账号
                        AppSettings.app("EmailPassword")                           // 邮箱密码/授权码
                    );
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;           // 通过网络发送

                    await client.SendMailAsync(mailMessage);  // 异步发送
                    return true;                              // 发送成功返回true
                }
            }
            catch (Exception ex)
            {
                // 使用日志框架记录异常
                Console.WriteLine($"邮件发送失败: {ex.Message}");
                return false;
            }
        }
    }
}
